package com.vic.framework.proxy;

import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vic.framework.annotation.Transaction;
import com.vic.framework.helper.DatabaseHrelper;

import jdk.nashorn.internal.ir.Flags;

/**
 * 事务代理
 * @author VIC
 *
 */
public class TransactionProxy implements Proxy {

	private static final Logger logger = LoggerFactory.getLogger(TransactionProxy.class);
	/**
	 * 此标志是为了 保证统一现成中事务控制相关逻辑只执行一次
	 */
	private static final ThreadLocal<Boolean> FLAG_HOLDER = new ThreadLocal<Boolean>(){
		protected Boolean initialValue(){
			return false;
		}
	};
	
	public Object doProxy(ProxyChain proxyChain) throws Throwable {
		Object result;
		boolean flag = FLAG_HOLDER.get();
		Method method = proxyChain.getTargetMethod();
		if(!flag && method.isAnnotationPresent(Transaction.class)) {
			FLAG_HOLDER.set(true);
			try{
				DatabaseHrelper.beginTransaction();
				logger.debug("begin transaction");
				result = proxyChain.doProxyChain();
				DatabaseHrelper.commitTransaction();
				logger.debug("commit transaction");
			}catch(Exception e){
				logger.error("rollback transaction");
				throw e;
			}
		}else {
			result = proxyChain.doProxyChain();
		}
		return result;
	}


}
